package com.darknight.opentools;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by DarKnight on 2017/7/11.
 */
public class RequestUtils {
    public static boolean isIE(String userAgent) {
        return StringUtils.containsIgnoreCase(userAgent, "MSIE") || StringUtils.containsIgnoreCase(userAgent, "Trident");
    }

    public static boolean isIE(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return isIE(userAgent);
    }

    public static String getEncodedFileName(String fileName, String userAgent) throws UnsupportedEncodingException {
        String encodeFileName;

        if(isIE(userAgent)) {
            encodeFileName = EncodeUtils.encode(fileName, "UTF-8");
        } else {
            byte[] utf8ByteAry = StringUtils.getBytesUtf8(fileName);
            encodeFileName = StringUtils.newStringIso8859_1(utf8ByteAry);
        }

        return encodeFileName;
    }

    public static String getEncodedFileName(String fileName, HttpServletRequest request) throws UnsupportedEncodingException {
        String encodeFileName;

        if(isIE(request)) {
            encodeFileName = EncodeUtils.encode(fileName, "UTF-8");
        } else {
            byte[] utf8ByteAry = StringUtils.getBytesUtf8(fileName);
            encodeFileName = StringUtils.newStringIso8859_1(utf8ByteAry);
        }

        return encodeFileName;
    }
}
